package loganalysis;

import java.io.*;
//import java.text.DateFormat;
import java.util.*;
import java.util.Date.*;
import java.text.SimpleDateFormat;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author prateek
 */
public class SummaryAnalysis {
    
    //Class Variables
    private int successfulTask;
    private int failedTask;
    private ArrayList<ArrayList<String>> logData ;
    private BufferedReader loadLogFile;
    private long timeStamp;
    private static BufferedReader loadInputFile;
    private double avgThroughput;
    
    public static void main(String [] args)
    {
     //String path= "/home/prateek/CS595/gto_linux_640GB/falkon_logs_history/logs_history/bgp/intrepid/zzhang/0654/logs/service/ion-R02-8/falkon_summary.txt";
     SummaryAnalysis obj =  new SummaryAnalysis();
     
     //reading summaylist.txt file
            try{
                    loadInputFile  = new BufferedReader(new FileReader ("/home/prateek/CS595/gto_linux_640GB/falkon_logs_history/logs_history/SumarryList.txt"));
                }catch(FileNotFoundException e )
                {
                 System.err.println("Error in List.txt : "+e);
                }
     
      //reading each falkon_summary.txt file for data writing data in summarygraph.txt
            String filePath="";
            try{
            
                 FileWriter intermidiateData = new FileWriter ("/home/prateek/CS595/gto_linux_640GB/falkon_logs_history/logs_history/summarygraph.txt" ,false);
                 BufferedWriter fileForGraph = new BufferedWriter(intermidiateData); 
                      while ((filePath=loadInputFile.readLine())!=null)
                         {  
                            System.out.println("-----------------------");
                             obj.ScanData(filePath);
                             try{
                                 if(obj.CheckEmptyFile())
                                    {
                                     obj.calculateTimeStamp();
                                     fileForGraph.write(obj.getTimeStamp()+" ");
                                     obj.taskCount();
                                     fileForGraph.write(obj.getSuccessfulTask()+" ");
                                     fileForGraph.write(obj.getFailedTask()+" ");
                                     obj.AverageThroughput();
                                     fileForGraph.write(Double.toString(obj.getAvgThroughput()));
                                      //Next line  
                                     fileForGraph.newLine();
                                    }
                                 
                             }catch(NumberFormatException i){System.out.println(" Number Format exception");fileForGraph.newLine();}
                             catch(IndexOutOfBoundsException e){System.err.println("falkon_summary.txt is empty");fileForGraph.newLine();} 
                             catch(ArithmeticException ae){System.err.println(" total task is zero  "+ae);fileForGraph.newLine();}
                            System.out.println("-----------------------"); 
                         }
                fileForGraph.close();
            }catch(IOException e )
            {
                System.err.println("File/Data not found in Summay_falkon.txt");
            }
             
             
     }
    
    public void ScanData(String filePath)
       {
            String fullFilePath = "/home/prateek/CS595/gto_linux_640GB/falkon_logs_history/logs_history/"+filePath;
            String line ="";
            //2D Array
         logData = new ArrayList<ArrayList<String>>();
             //Create file object and read it 
            try {
                       System.out.println(fullFilePath);
                       loadLogFile= new BufferedReader(new FileReader (fullFilePath));
                }
            catch(FileNotFoundException e)
                {
                    System.err.println("Error in finding log file: "+e);
                }
        //Initialize Row and column counter
         int row = 0;
         int col = 0;
         //Nested Loops to read file 
         try{
             while( (line = loadLogFile.readLine())!=null)
             {
                 Scanner scanLine = new Scanner(line);
                 logData.add(new ArrayList<String>());
                 while(scanLine.hasNext())
                 {
                     logData.get(row).add(scanLine.next());
                     col++;
                 }
                 row++;
             }
         
         }
         catch(IOException e)
         {
             System.err.println("Error in reading logs: "+e);
         }
              
       } 
    
    public void calculateTimeStamp ()
    {
    
        //Function to calculate the current time from epoch time on the log.
        
        timeStamp = Long.parseLong((logData.get(1).get(2)).replace("ms", ""));
      //  timeStampOfData =  this.EpochTimeCalculator(timeStamp);
           System.out.println("Time is "+timeStamp);
        //Removing the Top two rows 
         logData.remove(0);
         logData.remove(0);
    }
    
    //Contains count of success and failed task
    public void taskCount()
    {
        int i = logData.size();
        System.out.println("Num of Rows "+i);
        i--;
        successfulTask= Integer.parseInt(logData.get(i).get(14));
        System.out.println("Successful Task  "+successfulTask);
        failedTask = Integer.parseInt(logData.get(i).get(15));
        System.out.println("Failed Task  "+failedTask);
    }
    
    public void AverageThroughput()
    {
         Double total=0.0;
            int totalTask=successfulTask+failedTask;
            if(totalTask == 0)
            {
                throw new ArithmeticException();
            }
            System.out.println("Some random data "+logData.get(1).get(13));
            System.out.println("Total Num of Task "+totalTask);
            for (int i= 0;i<logData.size();i++)
                {
                   total+=Double.parseDouble(logData.get(i).get(13));
		  
                }
                System.out.println("Value of Total "+total);  
                avgThroughput=total/totalTask;
            System.out.println("Average Through put "+ avgThroughput);
            
    }
    
    public String EpochTimeCalculator(Long time)
    {
         Date epoch = new Date(time);
         SimpleDateFormat fDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
         String actualDate = fDate.format(epoch);
         return actualDate;
    }
    
    public boolean CheckEmptyFile ()
    {
        
         if(logData.get(0).get(0).isEmpty())
        {
        return false;
        }
         return true;
    
    } 
           

    
    //Getters & Setters

    public int getFailedTask() {
        return failedTask;
    }

    public int getSuccessfulTask() {
        return successfulTask;
    }

    public long getTimeStamp() {
        return timeStamp;
    }

    public double getAvgThroughput() {
        return avgThroughput;
    }
    
    
}
